package org.example.day;

import org.example.linkedlist.ListNode;

/**
 * @Description: Solution2
 * @Author wyatt
 * @Data 2024/06/25 22:05
 */
public class Solution2 {

    public static void main(String[] args) {

    }

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode head = null, tail = null;

        int carry = 0;
        while (l1 != null || l2 != null){
            int val1 = 0, val2 = 0;
            if(l1 != null){
                val1 = l1.val;
            }

            if(l2 != null){
                val2 = l2.val;
            }

            int val3 = (val1 + val2 + carry) % 10;
            if(head == null){
                head = tail = new ListNode(val3);
            }else {
                tail.next = new ListNode(val3);
                tail = tail.next;
            }

            carry = (val1 + val2 + carry) / 10;

            if(l1 != null){
                l1 = l1.next;
            }

            if(l2 != null){
                l2 = l2.next;
            }

        }

        if(carry > 0){
            tail.next = new ListNode(carry);
        }

        return head;
    }

}
